package com.sp.api.springbootapi.rabbitmq.topic;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by weidewang on 2018/7/11
 */
public class TopicRecv {
    private final static String QUEUE_NAME = "test_queue_topic_1";
    private final static String EXCHANGE_NAME = "test_exchange_topic";

    public static void main(String[] args) throws InterruptedException {
        Connection connection = null;
        final Channel channel;
        try {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            factory.setUsername("guest");
            factory.setPassword("guest");
            factory.setPort(5672);
            connection = factory.newConnection();
            channel = connection.createChannel();

            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            //绑定队列到交换器
            channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "goods.add");

            //统一时刻服务器只会发一条消息给消费者;
            channel.basicQos(1);
            //定义队列的消费者
            Consumer consumer = new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//                    channel.basicAck(envelope.getDeliveryTag(), false);
                    String message = new String(body,"UTF-8");
                    System.out.println(" [1] receive message：'" + message + "'");
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        System.out.println("[1] done");
                        channel.basicAck(envelope.getDeliveryTag(), false);
                    }

                }
            };

            channel.basicConsume(QUEUE_NAME,false,consumer);


        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
//            if (connection != null) {
//                try {
//                    connection.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
        }
    }

}
